<template>
    <xDataSpreadsheet class="p-reportClient"
        :config="config"
        :customConfig="customConfig"
        :templateData="templateData"
        :bindData="bindData"
        :loading="loading"
    >
        <template slot="toolbar">
            <!-- <Button @click="loadTemplate" type="primary">加载模板数据</Button> -->
            <form-create
                v-model="fapi" :rule="fields" :option="option" :value="formData"
                @submit="onSubmit" @change="onChange"
            ></form-create>
        </template>
    </xDataSpreadsheet>
</template>

<script>
import * as defaultTemplateData from '../detailWCCostConfig/templateData'
import { getYearOption, getMonthOption, getCurDate } from '../ProcessCostConfig/utils'
import xDataSpreadsheet from 'public/components/spreadSheet'

// excel的配置样式
let templateId = 34
// 统计模板模型的数据
let model = {
    type: 'statisticsTemplate', className: 'CostBreakdownWC'
}
export default {
    components: { xDataSpreadsheet },
    data() {
        let curDate = getCurDate()
        return {
            loading: false,
            config: {},
            templateId,
            model,
            customConfig: {
                showUpload: false,
                showExport: false,
                showSave: false,
                showLoadData: false,
                isReport: true
            },
            templateData: [],
            bindData: {},
            // 筛选表单formCreate的配置：http://www.form-create.com/v2/iview/global.html
            option: {
                form: {
                    inline: true,
                    labelPosition: "right",
                    labelWidth: 80,
                    hideRequiredAsterisk: false,
                    showMessage: true,
                    inlineMessage: true,
                    size: 'default'
                },
                global: {
                },
                submitBtn: {
                    innerText: '查询'
                },
                resetBtn: false
            },
            fapi: {},
            formData: {
                year: curDate.year, month: curDate.month, ...model,
            },
            fields: [
                // 配置项可以参考：http://www.form-create.com/v2/iview/components/input.html
                {
                    type: 'select', field: 'year', title: '年份', options: getYearOption(9),
                    effect:{ required: true },
                },
                {
                    type: 'select', field: 'month', title: '月份', options: getMonthOption(9),
                    effect:{ required: true }, 
                },
                {
                    type: 'input', field: 'type', title: 'type', props: { clearable: true}
                },
                {
                    type: 'input', field: 'className', title: 'className', props: { clearable: true}
                },
            ]
        }
    },
    beforeMount() {
        const params = new URLSearchParams(window.location.search)
        this.templateId = params.get('id') || this.templateId;
        console.log("🚀 ~ file: index.vue:36 ~ beforeMount", this.templateId)
    },
    mounted() {
        // 通过接口获取模板配置
        this.loadTemplate()

        // 通过接口获取绑定数据
        // setTimeout(() => {
        this.onSubmit()
        // }, 3000);
    },
    methods: {
        loadTemplate() {
            // this.templateData = defaultTemplateData.data
            // return;
            this.$api.PageReport.query({
                id: this.templateId
            }).then(res => {
                // console.log('loadTemplate', res);
                if (res && res.length && res[0].value && res[0].value.length) {
                    this.templateData = res[0].value
                } else {
                    this.templateData = defaultTemplateData.data
                }
            })
        },
        loadData() {
            // 通过api查询 绑定数据 ...
            this.loading = true
            // setTimeout(() => {
                let data = defaultTemplateData.mockBindData()
                this.bindData = data
                this.loading = false
            // }, 1000);
        },
        loadDataFromModel() {
            // CALCULATE
            this.loading = true
            this.$api.StatTemplateModel.calculate({
                condition: this.tools.getFilter({
                    type: this.fapi.form.type || model.type,
                    className: this.fapi.form.className || model.className,
                }),
                param: {
                    year: this.fapi.form.year,
                    month: this.fapi.form.month,
                    yearMonth: this.fapi.form.year +  this.fapi.form.month,
                    preYearMonth: this.fapi.form.year +''+  ((this.fapi.form.month - 1)<10?'0'+''+(this.fapi.form.month - 1):(this.fapi.form.month - 1)),
                }
            }).then(res=> {
                let list = []
                let basic = {}
                let testData = {
                    basic: [
                        {name : "date", title : "2023-04-12",  values : {}},
                        {name: 'name1', title : "name1-test", values : {}},
                        {name: 'name2', title : "", values: {name: 'name2-test'}},
                    ],
                    t1: [
                        {name : "name", title : "科目1", values : {}},
                        {name: 'dw', title : "单位", values : {result: '吨'}},
                        {
                            name: 'count1', title : "金额", saveTo: 'sf_result',
                            values : {sf_result: 160, count2: 122}
                        }
                    ],
                    t2: [
                        {name : "name", title : "科目2", values : {}},
                        {name: 'dw', title : "吨"},
                        {name: 'count1', title : "金额", values : {count1: 100}}
                    ]
                }
                let data = res
                Object.keys(data).forEach(key => {
                    let curItem = data[key];
                    basic['name'] = key;
                    curItem && curItem.length && curItem.forEach(item => {
                        if (item.values && Object.keys(item.values).length) {
                            Object.keys(item.values).forEach(valKey => {
                                if (item.name && item.saveTo === valKey) {
                                    basic[item.name] = item.values[valKey]
                                } else {
                                    basic[valKey] = item.values[valKey]
                                }
                            })
                        } else {
                            basic[item.name] = item.title
                        }
                    })
                })
                this.bindData = { ...basic};
                this.loading = false
                console.log("🚀 ~ file: client.vue ~ loadDataFromModel res: ", this.bindData)
            }).catch(err => {
                this.loading = false
            })
        },
        onSubmit() {
            // mock的数据
            // this.loadData()
            // 最终要使用的从模板模型读取
            this.loadDataFromModel()
        },
        onChange(field, value) {
            if (['year', 'month'].includes(field)) {
                // console.log("🚀 ~ file: client.vue:82 ~ onChange", field, value, this.fapi)
                this.onSubmit()
            }
        }
    }
}
</script>

<style lang="less">
.p-reportClient {
    .toolbar {
        padding-bottom: 0;
    }
    .ivu-form-item {
        margin-bottom: 16px;
    }
}
</style>